import { Router } from 'vue-router'
import { useUserStore } from '@/store/user'
import { isEmptyObject } from '@/utils'
import { registeredUserRoute } from '../shared'

export enum PageEnum {
  BASE_LOGIN = 'Login',
}

const whiteList: PageEnum[] = [PageEnum.BASE_LOGIN]

export default function setupPermissionGuard (router: Router) {
  // 权限路由守卫
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 过滤白名单
    const token = userStore.token
    if (whiteList.includes(to.name as PageEnum)) {
      // 白名单为登录时，直接跳转到首页
      if (to.name === PageEnum.BASE_LOGIN && token) {
        try {
          // 重新获取用户登录信息跳转到首页
          await registeredUserRoute()
          next('/')
        } catch {}
      }
      next()
      return
    }

    if (token) {
      if (isEmptyObject(userStore.userInfo)) {
        await registeredUserRoute()
        next({ ...to, replace: true })
        return
      }
      next()
      return
    }

    next('/login')
  })
}
